<template>
  <div class="myhome">
    <van-button type="info" @click="loginID">向地址连接</van-button>
    <van-button type="info" @click="doSubscribe">劢微云订阅</van-button>
    <van-button type="info" @click="destroyConnection">断开地址连接</van-button>
    <van-button type="primary" @click="docancel">车载取消订阅</van-button>
    <van-button type="primary" @click="doPublish">车载发布消息</van-button>
    <van-button type="primary" @click="getissue">车载发布订阅</van-button>
  </div>
</template>

<script>
//导入mqtt第三方包
import mqtt from "mqtt/dist/mqtt";
export default {
  data() {
    return {
      //向买微云进行登录的数据
      connection: {
        host: "test.multiway-cloud.com", //地址
        port: 8083, //端口号
        endpoint: "/mqtt", //重定向到mqtt协议
        clean: true, // 保留会话
        // connectTimeout: 4000, // 超时时间
        // reconnectPeriod: 1000, // 重连时间间隔
        // 认证信息
        clientId: "user5", //用户id
        username: this.$store.state.tokenObj, //保存的token
        password: "", //密码
      },
      //向劢微云订阅的数据
      subscription: {
        topic: "user1/vehicles",
        qos: 0,
      },
      //向车载订阅的数据内容
      CarSubscription: {
        topic: "vehicle1/map",
        qos: 1,
      },
      //向车载发送信息的数据
      publish: {
        topic: "user1/vehicle1",
        qos: 0,
        payload: '{"msg": "Hello","name":"飞天蝙蝠"}',
      },
      receiveNews: "",
      qosList: [
        { label: 0, value: 0 },
        { label: 1, value: 1 },
        { label: 2, value: 2 },
      ],
      client: {
        connected: false,
      },
      subscribeSuccess: false,
    };
  },

  created() {},
  //声明方法
  methods: {
    //使用webSocket发送请求
    // getWeb() {
    //   let ws = new WebSocket("ws://192.168.3.10:10009");
    //   ws.onmessage = (e) => {
    //     // console.log(e);
    //   };
    // },

    //拿到token后向服务器发起请求
    async loginID() {
      const { host, port, endpoint, ...options } = this.connection;
      const connectUrl = `ws://${host}:${port}${endpoint}`;
      try {
        this.client = mqtt.connect(connectUrl, options);
      } catch (error) {
        console.log("mqtt.connect error", error);
      }
      this.client.on("connect", () => {
        console.log("Connection succeeded!建立连接成功");
      });
      this.client.on("error", (error) => {
        console.log("Connection failed", error);
      });
      this.client.on("message", (topic, message) => {
        this.receiveNews = this.receiveNews.concat(message);
        console.log(`Received message ${message} from topic ${topic}`);
      });
    },

    //建立劢微云订阅的方法
    async doSubscribe() {
      const { topic, qos } = this.subscription;
      this.client.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log("Subscribe to topics error", error);
          return;
        }
        this.subscribeSuccess = true;
        console.log("Subscribe to topics res,订阅成功", res);
      });
    },

    //断开向劢微云的连接
    async destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end();
          this.client = {
            connected: false,
          };
          console.log("Successfully disconnected!,断开成功");
        } catch (error) {
          console.log("Disconnect failed", error.toString());
        }
      }
    },
    // 取消向车载订阅的方法
    async docancel() {
      const { topic } = this.CarSubscription;
      this.client.unsubscribe(topic, (error) => {
        if (error) {
          console.log("Unsubscribe error", error);
        } else {
          console.log("取消成功");
        }
      });
    },

    //向车载发布信息的方法
    doPublish() {
      const { topic, qos, payload } = this.publish;
      this.client.publish(topic, payload, qos, (error) => {
        if (error) {
          console.log("Publish error", error);
        } else {
          console.log("发布成功",payload);
        }
      });
    },
    //和车载这边订阅的方法
    getissue() {
      const { topic, qos } = this.CarSubscription;
      this.client.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log("Subscribe to topics error", error);
          return;
        }
        this.subscribeSuccess = true;
        console.log("Subscribe to topics res,订阅成功", res);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.van-button {
  margin-top: 20px;
  margin-left: 15px;
}
</style>
